<template>
  <el-dialog
      v-model="visible"
      :title="mode === 'add' ? '新增菜单' : '编辑菜单'"
      width="600px"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        label-position="right"
    >
      <el-form-item label="菜单类型" prop="menuType">
        <el-radio-group v-model="formData.menuType">
          <el-radio label="M">目录</el-radio>
          <el-radio label="C">菜单</el-radio>
          <el-radio label="F">按钮</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="上级菜单" prop="parentId">
        <el-tree-select
            v-model="formData.parentId"
            :data="menuTree"
            :props="treeProps"
            placeholder="请选择上级菜单"
            check-strictly
            clearable
            style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="菜单名称" prop="menuName">
        <el-input v-model="formData.menuName" placeholder="请输入菜单名称" />
      </el-form-item>

      <el-form-item label="排序" prop="orderNum">
        <el-input-number
            v-model="formData.orderNum"
            :min="0"
            controls-position="right"
        />
      </el-form-item>

      <template v-if="formData.menuType !== 'F'">
        <el-form-item label="路由地址" prop="path">
          <el-input v-model="formData.path" placeholder="请输入路由地址" />
        </el-form-item>

        <el-form-item label="组件路径" prop="component">
          <el-input v-model="formData.component" placeholder="请输入组件路径" />
        </el-form-item>
      </template>

      <el-form-item label="权限标识" prop="perms" v-if="formData.menuType === 'F'">
        <el-input v-model="formData.perms" placeholder="请输入权限标识" />
      </el-form-item>

      <el-form-item label="图标" prop="icon">
        <el-input v-model="formData.icon" placeholder="请输入图标名称" />
      </el-form-item>

      <el-form-item label="是否显示" prop="visible">
        <el-radio-group v-model="formData.visible">
          <el-radio label="0">显示</el-radio>
          <el-radio label="1">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio label="0">正常</el-radio>
          <el-radio label="1">停用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="是否缓存" prop="isCache" v-if="formData.menuType === 'C'">
        <el-radio-group v-model="formData.isCache">
          <el-radio :value="0">缓存</el-radio>
          <el-radio :value="1">不缓存</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getMenuTree, saveMenu, updateMenu } from '@/api/menu'

const props = defineProps({
  modelValue: Boolean,
  menuData: Object,
  mode: String
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(false)
const loading = ref(false)
const formRef = ref()
const menuTree = ref([])

const formData = reactive({
  menuType: 'C',
  parentId: 0,
  menuName: '',
  orderNum: 0,
  path: '',
  component: '',
  perms: '',
  icon: '',
  visible: '0',
  status: '0',
  isCache: 0,
  remark: ''
})

const treeProps = {
  value: 'menuId',
  label: 'menuName',
  children: 'children'
}

const rules = {
  menuName: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 50, message: '菜单名称长度在2-50个字符', trigger: 'blur' }
  ],
  orderNum: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入路由地址', trigger: 'blur' }
  ],
  perms: [
    { required: true, message: '请输入权限标识', trigger: 'blur' }
  ]
}

// 加载菜单树
const loadMenuTree = async () => {
  try {
    const response = await getMenuTree()
    if (response.code === 200) {
      menuTree.value = response.data
    }
  } catch (error) {
    console.error('加载菜单树失败:', error)
  }
}

// 处理对话框显示
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    loadMenuTree()
    if (props.mode === 'edit' && props.menuData) {
      Object.assign(formData, props.menuData)
      // 转换数字类型
      formData.isCache = Number(formData.isCache) || 0
    } else {
      resetForm()
    }
  }
})

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    menuType: 'C',
    parentId: 0,
    menuName: '',
    orderNum: 0,
    path: '',
    component: '',
    perms: '',
    icon: '',
    visible: '0',
    status: '0',
    isCache: 0,
    remark: ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false)
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  const valid = await formRef.value.validate()
  if (!valid) return

  loading.value = true
  try {
    if (props.mode === 'add') {
      await saveMenu(formData)
      ElMessage.success('新增成功')
    } else {
      await updateMenu(formData)
      ElMessage.success('更新成功')
    }
    emit('success')
    visible.value = false
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadMenuTree()
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
